<%#
kind: snippet
name: ca_registration
model: ProvisioningTemplate
snippet: true
description: |
  This template is used for updating Foreman's CA on hosts that are registered by Katello.
  It replaces the CA used by subscription-manager and adds the CA to trusted anchors.
-%>

<% if plugin_present?('katello') -%>
  # Define the path to the Katello server CA certificate
  KATELLO_SERVER_CA_CERT=/etc/rhsm/ca/katello-server-ca.pem

  # If katello ca cert file exists on host, update it and make sure it's in trust anchors
  if [ -f "$KATELLO_SERVER_CA_CERT" ]; then
    <%= save_to_file('"$KATELLO_SERVER_CA_CERT"', foreman_server_ca_cert) -%>

    . /etc/os-release

    if [ "$ID" = "debian" ] || [ "$ID_LIKE" = "debian" ]; then
      # update-ca-certificates is picky and only looks at .crt files
      CA_TRUST_ANCHOR_CERT=/usr/local/share/ca-certificates/katello-server-ca.crt
    elif [ "$ID" = "sles" ] || [ "$ID_LIKE" = "suse" ] || [ "$ID_LIKE" = "suse opensuse" ]; then
      CA_TRUST_ANCHOR_CERT=/etc/pki/trust/anchors/katello-server-ca.pem
    else
      CA_TRUST_ANCHOR_CERT=/etc/pki/ca-trust/source/anchors/katello-server-ca.pem
    fi

    # Add the Katello CA certificate to the system-wide CA certificate store
    cp $KATELLO_SERVER_CA_CERT $CA_TRUST_ANCHOR_CERT

    if [ "$ID" = "debian" ] || [ "$ID_LIKE" = "debian" ] || [ "$ID" = "sles" ] || [ "$ID_LIKE" = "suse" ] || [ "$ID_LIKE" = "suse opensuse" ]; then
      update-ca-certificates
    else
      update-ca-trust
    fi
  fi
<% end -%>
